import type { EzGameNet } from "./EzGameNet";

export class EzGameNetManager{
    private static readonly nets:Map<string,EzGameNet> = new Map();
    private static readonly pushMsgHandlers:Map<string,Map<number,PushMsgMeta<any>>> = new Map();

    public static register( net:EzGameNet):void {
        if(!net.name){
            throw new Error("网络注册失败！网络连接必须设置名称");
        }
        if(this.nets.has(net.name)) {
            throw new Error(`网络连接 ${name} 已经存在`);
        }
        this.nets.set(net.name, net);
    }
    public static unRegister( net:EzGameNet):void {
        if(!net.name){
            throw new Error("网络取消注册失败！网络连接必须设置名称");
        }
        if(this.nets.has(net.name)) {
            this.nets.delete(net.name);
            console.debug("网络连接已取消注册:", net.name);
            
        }

    }

    public static get(name:string):EzGameNet | null {
        if(!this.nets.has(name)) {
            return null;
        }
        return this.nets.get(name) || null;
    }

    public static getServerPushHandlerMap(name:string):Map<number,PushMsgMeta<any>> {
        if(!this.pushMsgHandlers.has(name)) {
            let map = new Map()
            this.pushMsgHandlers.set(name, map);
            return map;
        }
        return this.pushMsgHandlers.get(name);
    }
    public static getServerPushMeta(serverName:string,cmd:number):PushMsgMeta<any> | null {
        let handlerMap = this.getServerPushHandlerMap(serverName);
        if(!handlerMap.has(cmd)){
            return null;
        }
        return handlerMap.get(cmd) || null;
    }
}

export interface PushMsgMeta<T>{
    cmd:number
    decoder:(data:Uint8Array)=>T,
    handler?:Function
}